package com.luyou.smart.framewortk.helper;

import com.luyou.smart.framewortk.annotation.Inject;
import com.luyou.smart.framewortk.utils.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入助手类
 */
public class IocHelper {

    static {
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if(beanMap != null && beanMap.size() > 0){
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();
                //获取所有成员变量
                Field[] beanFields = beanClass.getDeclaredFields();
                for (Field beanField : beanFields) {
                    //检查是否有Inject注解
                    if(beanField.isAnnotationPresent(Inject.class)){
                        Class<?> beanFieldClass = beanField.getType();
                        Object beanFieldInstance = beanMap.get(beanFieldClass);
                        if(beanFieldInstance != null){
                            //通过反射初始化BeanField的值
                            ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                        }
                    }
                }
            }
        }
    }
}
